function fetchData(page = 1) {
    const perPage = $('#per_page').val();
    $.getJSON(`/data?page=${page}&per_page=${perPage}`, function(response) {
        $('#table-headers').empty();
        if (response.data.length > 0) {
            for (let key in response.headers) {
                $('#table-headers').append('<th>' + response.headers[key] + '</th>');
            }
        }

        $('#table-body').empty();
        response.data.forEach(item => {
            let row = '<tr>';
            for (let key in response.headers) {
                row += '<td>' + (item[response.headers[key]] || '') + '</td>';
            }
            row += '</tr>';
            $('#table-body').append(row);
        });

        $('#pagination').empty();
        const total_pages = Math.ceil(response.pagination.total / response.pagination.per_page);
        for (let i = 1; i <= total_pages; i++) {
            let active = (i === response.pagination.page) ? 'active' : '';
            $('#pagination').append('<li class="page-item ' + active + '"><a class="page-link" href="#" onclick="fetchData(' + i + ')">' + i + '</a></li>');
        }
    });
}

$(document).ready(function() {
    fetchData();
});
